<template>
  <div class="param-input">
    <!-- 计算参数（只读） -->
    <div v-if="param.paramType === 'calculation'" class="calculation-param">
      <el-form-item
        v-if="!tableMode"
        :label="getParamLabel(param)"
        :class="{ 'has-error': !isValid }"
      >
      <div style="display: flex;align-items: center;gap: 10px;">
        <div>
            <el-input
            v-model="displayValue"
            :placeholder="param.placeholder || '自动计算'"
            size="medium"
            disabled
          >
            <template slot="append" v-if="param.unit">{{ param.unit }}</template>
          </el-input>
          <div v-if="!isValid" class="error-message">{{ errorMessage }}</div>
        </div>  
        <span class="calculation-info">
          <el-tooltip :content="getCalculationInfo(param)" placement="top">
            <i class="el-icon-info"></i>
          </el-tooltip>
        </span>
      </div>
      </el-form-item>

      <!-- 表格模式 -->
      <div v-else class="cell-input">
        <el-input v-model="displayValue" disabled size="medium" />
        <div v-if="!isValid" class="error-message">{{ errorMessage }}</div>
      </div>
    </div>

    <!-- 多测次参数 -->
    <div
      v-else-if="param.isMultiMeasure && param.multiMeasureCount > 1"
      class="multi-measure-param"
    >
      <el-form-item v-if="!tableMode" :label="getParamLabel(param)" :required="param.validateRule.required">
        <div class="measure-inputs">
          <div v-for="(measure, index) in measureValues" :key="index" class="measure-item">
            <span class="measure-label">第{{ index + 1 }}测次</span>
            <component
              :is="getInputComponent(param.dataType)"
              v-model="measure.value"
              :param="param"
              @change="handleMeasureChange(index, $event)"
            />
          </div>
        </div>
      </el-form-item>

      <!-- 表格模式 -->
      <div v-else class="cell-input">
        <div v-for="(measure, index) in measureValues" :key="index" class="measure-item">
          <span class="measure-label">第{{ index + 1 }}测次</span>
          <component
            :is="getInputComponent(param.dataType)"
            v-model="measure.value"
            :param="param"
            @change="handleMeasureChange(index, $event)"
          />
        </div>
      </div>
    </div>

    <!-- 普通参数 -->
    <div v-else class="base-param">
      <el-form-item
        v-if="!tableMode"
        :label="getParamLabel(param)"
        :required="param.validateRule.required"
        :class="{ 'has-error': !isValid }"
      >
        <component
          :is="getInputComponent(param.dataType)"
          v-model="proxyValue"
          :param="param"
          @change="handleChange"
        />
        <div v-if="!isValid" class="error-message">{{ errorMessage }}</div>
      </el-form-item>

      <!-- 表格模式 -->
      <div v-else class="cell-input">
        <component
          :is="getInputComponent(param.dataType)"
          v-model="proxyValue"
          :param="param"
          @change="handleChange"
        />
        <div v-if="!isValid" class="error-message">{{ errorMessage }}</div>
      </div>
    </div>
  </div>
</template>

<script>
// 导入子输入组件（简化实现，实际项目可扩展）
import TextInput from './input-types/TextInput.vue'
import NumberInput from './input-types/NumberInput.vue'
import SelectInput from './input-types/SelectInput.vue'
import DateInput from './input-types/DateInput.vue'
import TextareaInput from './input-types/TextareaInput.vue'
import BooleanInput from './input-types/BooleanInput.vue'

export default {
  name: 'ParamInput',
  components: {
    TextInput, NumberInput, SelectInput, DateInput, TextareaInput, BooleanInput
  },
  props: {
    param: {
      type: Object,
      required: true,
      default: () => ({}) // 兜底空对象，避免缺失prop警告
    },
    value: {
      type: [Object, Array, String, Number],
      default: () => ({ value: '', isValid: true, message: '' })
    },
    rowIndex: {
      type: Number,
      default: null
    },
    tableMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      currentValue: this.normalizeValue(this.value),
      measureValues: []
    }
  },
  computed: {
    // 计算参数显示值
    displayValue() {
      return this.param.paramType === 'calculation'
        ? this.currentValue.value || '-'
        : ''
    },
    // 验证状态
    isValid() {
      return this.currentValue.isValid
    },
    // 错误信息
    errorMessage() {
      return this.currentValue.message
    },
    // 普通参数双向绑定代理
    proxyValue: {
      get() {
        return this.currentValue.value
      },
      set(val) {
        this.currentValue.value = val
        this.handleChange(this.currentValue)
      }
    }
  },
  watch: {
    value: {
      handler(newVal) {
        this.currentValue = this.normalizeValue(newVal)
        if (this.param.isMultiMeasure && this.param.multiMeasureCount > 1) {
          this.initializeMeasureValues()
        }
      },
      immediate: true,
      deep: true
    },
    param: {
      handler(newParam) {
        if (newParam.isMultiMeasure && newParam.multiMeasureCount > 1) {
          this.initializeMeasureValues()
        }
      },
      immediate: true,
      deep: true
    }
  },
  created() {
    if (this.param.isMultiMeasure && this.param.multiMeasureCount > 1) {
      this.initializeMeasureValues()
    }
  },
  methods: {
    // 初始化多测次参数值
    initializeMeasureValues() {
      if (!this.param.multiMeasureCount || this.param.multiMeasureCount < 1) {
        this.measureValues = []
        return
      }

      if (Array.isArray(this.currentValue)) {
        this.measureValues = [...this.currentValue]
      } else {
        this.measureValues = Array.from({ length: this.param.multiMeasureCount }, () => ({
          value: '',
          isValid: true,
          message: ''
        }))
      }
    },

    // 规范化值格式
    normalizeValue(val) {
      if (Array.isArray(val)) return val
      if (val && typeof val === 'object' && 'value' in val) return val
      return {
        value: val !== undefined && val !== null ? val : '',
        isValid: true,
        message: ''
      }
    },

    // 获取参数标签
    getParamLabel(param) {
      let label = param.paramName || param.paramCode || '未命名参数'
      if (param.unit && param.paramType !== 'calculation') {
        label += ` (${param.unit})`
      }
      return label
    },

    // 根据数据类型获取输入组件
    getInputComponent(dataType) {
      const componentMap = {
        text: 'TextInput',
        number: 'NumberInput',
        select: 'SelectInput',
        date: 'DateInput',
        textarea: 'TextareaInput',
        boolean: 'BooleanInput'
      }
      return componentMap[dataType] || 'TextInput'
    },

    // 获取计算参数信息（公式+依赖）
    getCalculationInfo(param) {
      if (param.paramType !== 'calculation') return ''
      const deps = param.dependencies || []
      return `公式: ${param.calculationExpr || '无'}\n依赖: ${deps.join(', ')}`
    },

       /**
     * 统一参数验证方法
     */
    validateParam(value, param) {
      const rules = param.validateRule || {}
      let isValid = true
      let message = ''

      // 1. 必填验证
      if (rules.required && (value === '' || value === null || value === undefined)) {
        isValid = false
        message = rules.requiredMsg || '此字段为必填项'
        return { isValid, message }
      }

      // 空值且非必填时直接通过
      if (value === '' || value === null || value === undefined) {
        return { isValid: true, message: '' }
      }

      // 2. 数值范围验证（仅对数字类型）
      if (param.dataType === 'number') {
        const numValue = Number(value)
        
        if (!isNaN(numValue)) {
          // 最小值验证
          if (rules.min !== undefined && numValue < rules.min) {
            isValid = false
            message = rules.rangeMsg || `数值不能小于 ${rules.min}`
          }
          
          // 最大值验证
          if (isValid && rules.max !== undefined && numValue > rules.max) {
            isValid = false
            message = rules.rangeMsg || `数值不能大于 ${rules.max}`
          }
        }
      }

      // 3. 文本长度验证（仅对文本类型）
      if (param.dataType === 'text' || param.dataType === 'textarea') {
        const strValue = String(value)
        
        // 最小长度验证
        if (rules.minLength && strValue.length < rules.minLength) {
          isValid = false
          message = rules.lengthMsg || `内容长度不能少于 ${rules.minLength} 个字符`
        }
        
        // 最大长度验证
        if (isValid && rules.maxLength && strValue.length > rules.maxLength) {
          isValid = false
          message = rules.lengthMsg || `内容长度不能超过 ${rules.maxLength} 个字符`
        }
      }

      // 4. 正则表达式验证
      if (isValid && rules.pattern) {
        const regex = new RegExp(rules.pattern)
        if (!regex.test(String(value))) {
          isValid = false
          message = rules.patternMsg || '格式不符合要求'
        }
      }

      return { isValid, message }
    },

 /**
     * 处理普通参数变化 - 增强验证
     */
    handleChange(newVal) {
      const finalValue = typeof newVal === 'object' && 'value' in newVal
        ? newVal
        : { ...this.currentValue, value: newVal }

      // 执行验证
      const validation = this.validateParam(finalValue.value, this.param)
      finalValue.isValid = validation.isValid
      finalValue.message = validation.message

      this.currentValue = finalValue
      this.$emit('change', finalValue)
    },

    /**
     * 处理多测次参数变化 - 增强验证
     */
    handleMeasureChange(index, newVal) {
      if (this.measureValues[index]) {
        const finalValue = typeof newVal === 'object' && 'value' in newVal
          ? newVal
          : { ...this.measureValues[index], value: newVal }

        // 执行验证
        const validation = this.validateParam(finalValue.value, this.param)
        finalValue.isValid = validation.isValid
        finalValue.message = validation.message

        this.measureValues[index] = finalValue
        this.$emit('change', [...this.measureValues])
      }
    }
  }
}
</script>

<style scoped>
.param-input {
  width: 100%;
}

.cell-input {
  display: inline-block;
  width: 100%;
}

.measure-inputs {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.measure-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 0;
}

.measure-label {
  font-size: 12px;
  color: #909399;
  min-width: 50px;
  text-align: right;
}

.has-error :deep(.el-input__inner) {
  border-color: #f56c6c;
}

.error-message {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 4px;
}

.calculation-info {
  margin-top: 4px;
}

.calculation-info .el-icon-info {
  color: #909399;
  cursor: help;
}

/* 表格模式样式适配 */
.table-mode :deep(.el-input) {
  width: 100%;
}
</style>